﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.Framework.Commons;
using IGM.Framework.Constants;

namespace IGM.Presentation.Management
{
    public partial class LecturersControl : UserControl
    {
        private readonly Business.Business _business;

        public LecturersControl()
        {
            InitializeComponent();

            _business = Main.Main.Instance.IgmBusiness;
        }

        private void LecturersControlLoad(object sender, EventArgs e)
        {
            LoadMajor();
            LoadLecturer();
            Dock = DockStyle.Top;
        }

        #region -- Lecturer --

        private void LoadMajor()
        {
            cboMajors.DataSource = _business.GetListMajor();
            cboMajors.DisplayMember = PropertiesConstants.Name;
            cboMajors.ValueMember = PropertiesConstants.Id;
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadLecturer()
        {
            dgvLecturers.DataSource = _business.GetListLecturerByMajorId(((Major) cboMajors.SelectedItem).Id);
            DataGridViewHelper.ShowHideColumns(dgvLecturers,
                                               new[] { PropertiesConstants.IsChecked, PropertiesConstants.Name, "DateOfBirth", "UniversityDegree" });
            DataGridViewHelper.ShowIsCheck(dgvLecturers);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvLecturers, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvLecturers, new[] { "IsChecked", "Name", "DateOfBirth", "UniversityDegree" },
                                                   new[] { "Chọn", "Họ và tên", "Ngày tháng năm sinh", "Học vị" });

            LecturerCurrentRowChanged();
        }

        private void LecturerCurrentRowChanged()
        {
            if (dgvLecturers.CurrentRow != null)
            {
                txtName.Text = dgvLecturers.CurrentRow.Cells["Name"].Value.ToString();
                cboUniversityDegree.Text = dgvLecturers.CurrentRow.Cells["UniversityDegree"].Value.ToString();           
            }

            else
            {
                txtName.Text = cboUniversityDegree.Text = string.Empty;
                ckbAllLecturers.Checked = false;
                dtpBirthday.Value = DateTime.Now;
            }
        }

        private void CboMajorsSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadLecturer();
        }

        private void DgvLecturersCurrentCellChanged(object sender, EventArgs e)
        {
            LecturerCurrentRowChanged();
        }

        private void DgvLecturersCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvLecturers == null ||
               dgvLecturers.Columns[(string)typeof(Lecturer).Properties().IsChecked] == null ||
               dgvLecturers.Columns[(string)typeof(Lecturer).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvLecturers[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvLecturers[e.ColumnIndex, e.RowIndex].Value;

            ckbAllLecturers.Checked = DataGridViewHelper.AllRowsIsCheck(dgvLecturers);
        }

        private void CkbAllLecturersCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvLecturers, ckbAllLecturers.Checked);
        }

        private void ReloadLecturer(Lecturer lecturer)
        {
            LoadLecturer();
            DataGridViewHelper.SetDgvCurrentCell(dgvLecturers, lecturer.Name);
            LecturerCurrentRowChanged();
        }

        /// <summary>
        /// Event click button Add Lecturer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddLecturerClick(object sender, EventArgs e)
        {
            try
            {
                var lecturer = new Lecturer{
                                       Name = txtName.Text.Trim(),                                   
                                       IdMajor = ((Major) cboMajors.SelectedItem).Id,
                                       DateOfBirth = dtpBirthday.Value,
                                       UniversityDegree = cboUniversityDegree.SelectedItem.ToString() };

                string message;

                if (_business.AddLecturerValidator(lecturer, out message))
                {
                    _business.AddLecturer(lecturer);

                    ReloadLecturer(lecturer);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click edit Major
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditLecturerClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvLecturers.CurrentRow != null)
                {
                    var lecturer = new Lecturer
                    {
                       Id = Convert.ToInt32(dgvLecturers.CurrentRow.Cells[PropertiesConstants.Id].Value),
                       Name = txtName.Text.Trim(),                   
                       DateOfBirth = dtpBirthday.Value,
                       UniversityDegree = cboUniversityDegree.SelectedItem.ToString(),
                       IdMajor = ((Major)cboMajors.SelectedItem).Id
                    };
                    string message;
                    if (_business.EditLecturerValidator(lecturer, out message))
                    {
                        if (!_business.EditLecturer(lecturer))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                            return;
                        }
                        ReloadLecturer(lecturer);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click Delete Lecturer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteLecturerClick(object sender, EventArgs e)
        {
            try
            {
                var lecturers = new List<Lecturer>();
                string message;
                
                for (var i = 0; i < dgvLecturers.RowCount; i++)
                {
                    if (!(bool)dgvLecturers[(string)typeof(Lecturer).Properties().IsChecked, i].Value) continue;
                    lecturers.Add(new Lecturer
                    {
                        Id = (int)dgvLecturers[(string)typeof(Lecturer).Properties().Id, i].Value,
                        Name = dgvLecturers[(string)typeof(Lecturer).Properties().Name, i].Value.ToString(),                   
                        IdMajor = ((Major)cboMajors.SelectedItem).Id,
                        DateOfBirth = (DateTime?) dgvLecturers["DateOfBirth", i].Value,
                        UniversityDegree = dgvLecturers["UniversityDegree", i].Value.ToString()
                    });
                }
                MessageBox.Show(lecturers.Count.ToString());
                if (lecturers.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (_business.DeleteLecturersValidator(lecturers, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các giảng viên đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteLecturers(lecturers);
                        ReloadLecturer(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion

        private void ptbImportData_Click(object sender, EventArgs e)
        {
            //Import data
        }
    }
}
